package handle

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-flow/cache"
	"logi-flow/model"
	"strconv"
	"time"
)

func PersonAdd(c *gin.Context) {
	person_code := c.PostForm("person_code")
	person_name := c.PostForm("person_name")
	person_tel := c.PostForm("person_tel")

	data := model.Person{

		PerCode: person_code,
		PerName: person_name,
		PerTel:  person_tel,
	}

	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_address := c.PostForm("order_address")
	pid, _ := strconv.Atoi(c.PostForm("pid"))

	data := model.PersonOrder{

		OrderCode:    order_code,
		OrderName:    order_name,
		OrderAddress: order_address,
		Pid:          pid,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var order []model.PersonOrder
	redis_key := "person_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Model(&model.PersonOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  order,
		"total": total,
	})
	return
}

func PersonOrderList(c *gin.Context) {

	/*
		SELECT
		  people.per_code AS PerCode,
		  people.per_name AS PerName,
		  people.per_tel AS PerTel,
		  person_orders.order_code AS OrderCode,
		  person_orders.order_name as OrderName,
		  person_orders.order_address as OrderAddress
		FROM
		  people
		  LEFT JOIN person_orders ON people.id = person_orders.pid
	*/

	var order []model.PersonOrder
	redis_key := "order_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("people").
			Select("people.per_code AS PerCode",
				"people.per_name AS PerName",
				"people.per_tel AS PerTel",
				"person_orders.order_code AS OrderCode",
				"person_orders.order_name as OrderName",
				" person_orders.order_address as OrderAddress",
			).Joins("LEFT JOIN person_orders ON people.id = person_orders.pid").
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	var total int64
	model.DB.Model(&model.PersonOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  order,
		"total": total,
	})
	return

}
